//
//  Analyzers.swift
//  AjaxRequestResponse
//
//  Created by Bob.Su on 16/2/22.
//  Copyright © 2016年 infitecs. All rights reserved.
//

import ObjectMapper

typealias OMMappable = Mappable

class ObjectAnalyzer <T: Mappable> {
    
    #if DEBUG
    var description : String?
    init(description: String) {
        self.description = description
    }
    #endif
    
    init() {
    }
    
    func analyze(json: AnyObject, toObject: T) {
        Mapper<T>().map(json, toObject: toObject)
    }
    
    func analyze(json: AnyObject) -> T? {
        if let object = Mapper<T>().map(json){
            return object
        }
        #if DEBUG
            print("解析JSON -> Mappable失败 - \(description)")
        #endif
        return nil
    }
}

class ArrayAnalyzer <T: Mappable> {
    var name : String?

    func analyze(json: AnyObject) -> [T]? {
        if let object = Mapper<T>().mapArray(json){
            return object
        }
        #if DEBUG
            var description : String = ""
            if let name = self.name {
                description = " - \(name)"
            }
            print("解析JSON -> Array<Mappable>失败\(description)")
        #endif
        return nil
    }
}

extension Mappable {
    func oBool2JInt () ->  TransformOf<Bool, Int> {
        return TransformOf<Bool, Int> (
            fromJSON: { (value: Int?) -> Bool? in
                if let value = value {
                    return value != 0
                }
                return nil
            }, toJSON: { (value: Bool?) -> Int? in
                // transform value from Int? to String?
                if let value = value {
                    if value {
                        return 1
                    } else {
                        return 0
                    }
                }
                return nil
        })
    }
}